# coding:utf-8

# -?表示没有解决，还有不懂的。

# 2、如何在一个函数内部修改全局变量

a = 3


def s():
    global a
    a = 4
    print('inner a=', a)


print('first a=', a)
s()
print('last a=', a)

# first a= 3
# inner a= 4
# last a= 4


# Note:
# global修饰变量时不能直接赋值
# 函数外定义的默认是全局变量

# error:
b = 1
# def global_test():
#     global b=2
#     print(b)


# gcount = 0
#
# def global_test():
#     gcount+=1
#     print (gcount)
# global_test() # UnboundLocalError: local variable 'gcount' referenced before assignment


def make_counter():
    count = 0

    def counter():
        nonlocal count
        count += 1
        return count

    return counter


def make_counter_test():
    mc = make_counter()
    print(mc())
    print(mc())
    print(mc())


make_counter_test()


print('-----')


def scope_test():
    def do_global():
        global spam
        spam = "global spam"

    spam = "test spam"
    print(spam)
    do_global()
    print("After global assignment:", spam)  # After global assignment: test spam


scope_test()
print("In global scope:", spam)  # In global scope: global spam


# def add_b():
#     global  b
#     b = 42
#     def do_global():
#         global  b
#         b = b + 10
#         print(b)
#     do_global()
#     print(b)
# add_b()
#
# def add_b():
#     global  b
#     b = 42
#     def do_global():
#         #global  b
#         # b = b + 10
#         print(b)
#     do_global()
#     print(b)
# add_b()